<?php
if (!file_exists('../install.lock')) {
    header('Location: ../install.php');
    exit;
}
session_start();
require_once '../config.php';

// 检查是否登录
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// 获取系统设置
$settings = getSettings();
$error = '';
$success = '';

// 处理生成卡密
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $count = intval($_POST['count'] ?? 0);
    $card_type = $_POST['card_type'] ?? 'day';
    $card_value = intval($_POST['card_value'] ?? 0);
    $max_uses = intval($_POST['max_uses'] ?? 0);
    
    // 验证时长值不超过限制
    switch ($card_type) {
        case 'minute':
            $card_value = min($card_value, 59);
            break;
        case 'hour':
            $card_value = min($card_value, 23);
            break;
        case 'day':
            $card_value = min($card_value, 30);
            break;
        case 'week':
            $card_value = min($card_value, 4);
            break;
        case 'month':
            $card_value = min($card_value, 11);
            break;
        case 'season':
            $card_value = min($card_value, 3);
            break;
    }
    
    // 类型与单位映射
    $type_map = [
        'minute' => '分钟卡',
        'hour' => '小时卡',
        'day' => '天卡',
        'week' => '周卡',
        'month' => '月卡',
        'season' => '季卡',
        'year' => '年卡',
        'forever' => '永久卡',
    ];
    
    if ($count > 0) {
        try {
            $stmt = $pdo->prepare("INSERT INTO kami (kami_key, expire_time, max_uses, created_by, type) VALUES (?, ?, ?, ?, ?)");
            $generated = 0;
            for ($i = 0; $i < $count; $i++) {
                $kami_key = generatekamiKey();
                $expire_time = null;
                $type_label = $type_map[$card_type] ?? '天卡';
                if ($card_type !== 'forever') {
                    if ($card_value > 0) {
                        switch ($card_type) {
                            case 'minute':
                                $expire_time = date('Y-m-d H:i:s', strtotime("+{$card_value} minutes"));
                                break;
                            case 'hour':
                                $expire_time = date('Y-m-d H:i:s', strtotime("+{$card_value} hours"));
                                break;
                            case 'day':
                                $expire_time = date('Y-m-d H:i:s', strtotime("+{$card_value} days"));
                                break;
                            case 'week':
                                $expire_time = date('Y-m-d H:i:s', strtotime("+{$card_value} weeks"));
                                break;
                            case 'month':
                                $expire_time = date('Y-m-d H:i:s', strtotime("+{$card_value} months"));
                                break;
                            case 'season':
                                $expire_time = date('Y-m-d H:i:s', strtotime("+".($card_value*3)." months"));
                                break;
                            case 'year':
                                $expire_time = date('Y-m-d H:i:s', strtotime("+{$card_value} years"));
                                break;
                        }
                    }
                } else {
                    $type_label = '永久卡';
                    $expire_time = null; // 永久卡
                }
                $stmt->execute([
                    $kami_key,
                    $expire_time,
                    0, // 设置为0表示无限制使用次数
                    $_SESSION['admin_id'],
                    $type_label
                ]);
                $_SESSION['generated_kami'][] = $kami_key;
                $generated++;
            }
            $_SESSION['success'] = "成功生成 {$generated} 个卡密";
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        } catch (PDOException $e) {
            $_SESSION['error'] = '生成卡密失败：' . $e->getMessage();
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        }
    } else {
        $_SESSION['error'] = '请指定要生成的卡密数量';
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
}

// 获取会话消息
$error = $_SESSION['error'] ?? '';
$success = $_SESSION['success'] ?? '';
// 清除会话消息
unset($_SESSION['error'], $_SESSION['success']);

// 生成卡密函数
function generatekamiKey() {
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $key = '';
    for ($i = 0; $i < 16; $i++) {
        $key .= $chars[rand(0, strlen($chars) - 1)];
        if ($i > 0 && $i % 4 === 3 && $i < 15) {
            $key .= '-';
        }
    }
    return $key;
}
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title><?php echo htmlspecialchars($settings['title']); ?> - 生成卡密</title>
    <link rel="shortcut icon" type="image/x-icon" href="../assets//favicon.ico">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <link rel="stylesheet" type="text/css" href="../assets//css/materialdesignicons.min.css">
    <link rel="stylesheet" type="text/css" href="../assets//css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/animate.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/style.min.css">
</head>

<body>
<!--页面loading-->
<div id="lyear-preloader" class="loading">
    <div class="ctn-preloader">
        <div class="round_spinner">
            <div class="spinner"></div>
            <img src="../assets/images/loading-logo.png" alt="">
        </div>
    </div>
</div>
<!--页面loading end-->

<div class="lyear-layout-web">
    <div class="lyear-layout-container">
        <?php $current_page = 'kami_generate'; include 'navbar.php'; ?>
        
        <!--页面主要内容-->
        <main class="lyear-layout-content">
            <div class="container-fluid p-t-15">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-header">
                                <h4>生成新卡密</h4>
                            </div>
                            <div class="card-body">
                                <?php if ($error): ?>
                                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                        <strong>错误！</strong> <?php echo $error; ?>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($success): ?>
                                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                                        <strong>成功！</strong> <?php echo $success; ?>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                    </div>
                                    
                                    <?php if (isset($_SESSION['generated_kami']) && !empty($_SESSION['generated_kami'])): ?>
                                        <div class="card">
                                            <div class="card-header d-flex justify-content-between align-items-center">
                                                <h4 class="mb-0">生成的卡密</h4>
                                                <button type="button" id="copy-all-btn" class="btn btn-info">
                                                    <i class="mdi mdi-content-copy"></i> 复制所有卡密
                                                </button>
                                            </div>
                                            <div class="card-body">
                                                <div class="form-group">
                                                    <textarea id="kami-list" class="form-control" rows="10" readonly><?php echo implode("\n", $_SESSION['generated_kami']); ?></textarea>
                                                </div>
                                            </div>
                                        </div>
                                        <?php unset($_SESSION['generated_kami']); ?>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <form action="" method="post" class="row g-3">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="count" class="form-label">生成数量</label>
                                            <input type="number" class="form-control" id="count" name="count" value="1" min="1" max="100" required>
                                            <small class="form-text text-muted">一次最多生成100个卡密</small>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="card_type" class="form-label">卡密类型</label>
                                            <select class="form-control" id="card_type" name="card_type">
                                                <option value="minute">分钟卡</option>
                                                <option value="hour">小时卡</option>
                                                <option value="day" selected>天卡</option>
                                                <option value="week">周卡</option>
                                                <option value="month">月卡</option>
                                                <option value="season">季卡</option>
                                                <option value="year">年卡</option>
                                                <option value="forever">永久卡</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-6" id="card_value_container">
                                        <div class="mb-3">
                                            <label for="card_value" class="form-label">时长值</label>
                                            <input type="number" class="form-control" id="card_value" name="card_value" value="1" min="1" max="31">
                                            <small class="form-text text-muted">根据卡密类型，时长值会有不同的限制：分钟卡(最大59)、小时卡(最大23)、天卡(最大30)、周卡(最大4)、月卡(最大11)、季卡(最大3)</small>
                                        </div>
                                    </div>
                                    
                                    <!-- 隐藏最大使用次数输入框，但保留表单字段 -->
                                    <input type="hidden" id="max_uses" name="max_uses" value="0">
                                    
                                    <div class="col-12">
                                        <button type="submit" class="btn btn-primary">生成卡密</button>
                                        <button type="reset" class="btn btn-default">重置</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
        <!--End 页面主要内容-->
    </div>
</div>

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript" src="../assets/js/popper.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../assets/js/perfect-scrollbar.min.js"></script>
<script type="text/javascript" src="../assets/js/jquery.mCustomScrollbar.concat.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap-notify.min.js"></script>
<script type="text/javascript" src="../assets/js/main.min.js"></script>
<script>
$(document).ready(function() {
    // 初始化检查卡密类型
    checkCardType();
    
    // 卡密类型变化时，控制时长值的显示/隐藏
    $('#card_type').change(function() {
        checkCardType();
    });
    
    // 检查卡密类型并相应地显示/隐藏时长值输入框
    function checkCardType() {
        var cardType = $('#card_type').val();
        
        // 设置不同类型卡密的最大时长限制
        var maxValue = 1;
        switch(cardType) {
            case 'minute':
                maxValue = 59;
                break;
            case 'hour':
                maxValue = 23;
                break;
            case 'day':
                maxValue = 30;
                break;
            case 'week':
                maxValue = 4;
                break;
            case 'month':
                maxValue = 11;
                break;
            case 'season':
                maxValue = 3;
                break;
            case 'year':
                maxValue = 100; // 年卡没有特定限制，设置一个较大的值
                break;
        }
        
        // 更新时长值输入框的最大值
        $('#card_value').attr('max', maxValue);
        
        // 如果当前值超过最大值，则设置为最大值
        if (parseInt($('#card_value').val()) > maxValue) {
            $('#card_value').val(maxValue);
        }
        
        if (cardType === 'forever') {
            $('#card_value_container').hide();
            $('#card_value').prop('disabled', true);
        } else {
            $('#card_value_container').show();
            $('#card_value').prop('disabled', false);
            if ($('#card_value').val() == 0) {
                $('#card_value').val(1);
            }
        }
    }
    
    // 复制所有卡密
    $('#copy-all-btn').click(function() {
        var kamiList = $('#kami-list');
        kamiList.select();
        document.execCommand('copy');
        
        $.notify({
            message: '卡密已复制到剪贴板'
        },{
            type: 'success',
            placement: {
                from: 'top',
                align: 'center'
            },
            z_index: 10800,
            delay: 1500,
            animate: {
                enter: 'animate__animated animate__fadeInDown',
                exit: 'animate__animated animate__fadeOutUp'
            }
        });
    });
});
</script>
</body>
</html> 